﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace Odyssey.Web.Controllers
{
    public class FileController : Controller
    {
        [HttpPost]
        public ActionResult Upload()
        {
            return SaveFile("logo");
        }

        [HttpPost]
        public ActionResult UploadPhoto()
        {
            return SaveFile("photo");
        }

        protected ActionResult SaveFile(string dir)
        {
            var path = Path.Combine(Server.MapPath("/"), "uploadfiles");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = Path.Combine(path, dir);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            try
            {
                Stream stream;
                string sourceName;
                if (Request.Files.Count > 0)
                {
                    stream = Request.Files[0].InputStream;
                    sourceName = Request.Files[0].FileName;
                }
                else
                {
                    stream = Request.InputStream;
                    sourceName = Request.QueryString["qqfile"];
                }
                string fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(sourceName);
                var file = Path.Combine(path, fileName);
                var buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                System.IO.File.WriteAllBytes(file, buffer);

                return Json(new { success = true, fileName = "/uploadfiles/" + dir + "/" + fileName }, "text/json");
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message }, "application/json");
            }


        }
    }
}